" This config file is prepared for Neovim in mind.
" 1. Install neovim, git, xclip, ag, the_silver_searcher package on your 
" Linux system.
" sudo pacman -S neovim git xclip the_silver_searcher
" 2. Install vim-plug (https://github.com/junegunn/vim-plug)
" to manage packages easily. On Linux:
" mkdir -p ~/.local/share/nvim/site/autoload/
" curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
" 3. To stop a python related error for UltiSnips:
" sudo pacman -S python-pip
" pip3 install --upgrade pip
" pip3 install --user neovim
" pip3 install --user typing
" 4. Save this file as init.vim:
" mkdir -p ~/.config/nvim
" nano ~/.config/nvim/init.vim
" 5. Run nvim in terminal, ignore the errors,
" then run :PlugInstall
" . When it says "Finishing...Done!" :q to quit the screen. and then :UpdateRemotePlugins from inside neovim. Quit neovim, restart and use.
" 6. To check keyboard Shortcuts, check the mapping commands

" -------------- Start vim-plug --------------- "

" Specify a directory for plugins
" - For Neovim: ~/.local/share/nvim/plugged
" - For Vim: ~/.vim/plugged
" - Avoid using standard Vim directory names like 'plugin'
call plug#begin('~/.local/share/nvim/plugged')


" -- Custom Plugins -- "
" Run :PlugInstall after adding a plugin
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }
Plug 'crusoexia/vim-monokai'
Plug 'ervandew/supertab'
Plug 'scrooloose/nerdcommenter'
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'
" Requires system package: ack, optional: the_silver_searcher
Plug 'mileszs/ack.vim'
Plug 'terryma/vim-multiple-cursors'
Plug 'kien/ctrlp.vim'
Plug 'shinokada/dragvisuals.vim'
" will need to run :UpdateRemotePlugins for this
Plug 'Shougo/denite.nvim'
Plug 'Chiel92/vim-autoformat'
Plug 'severin-lemaignan/vim-minimap'
"
Plug 'tobyS/vmustache'
Plug 'tobyS/pdv'
" autocomplete
"Plug 'roxma/LanguageServer-php-neovim',  {'do': 'composer install && "composer run-script parse-stubs'}
Plug 'roxma/nvim-completion-manager'
"Plug 'roxma/python-support.nvim'
Plug 'shawncplus/phpcomplete.vim'

" Initialize plugin system
call plug#end()

" -------------- End vim-plug --------------- "


" -------- General Configs -------- "


" -- general general configs -- "
syntax on
filetype plugin indent on
"filetype plugin on
syntax on
colorscheme monokai
set cursorline      " Highlight cursor line
" highlight long lines
" more helpful than "set textwidth=80"
highlight ColorColumn ctermbg=magenta
call matchadd('ColorColumn', '\%81v', 100)
" for invisible characters
set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<,space:␣
"highlight SpecialKey ctermfg=8 ctermbg=8
"highlight link VisibleTab Error
"match VisibleTab /\t$/

" -- show row and column in footer + improved statusbar -- "
set ruler
set statusline=%F%m%r%h%w\ [%l,%c]\ [%L,%p%%]

" -- so that : commands can be typed quick! -- "
nnoremap ; :

" -- use mouse cursor (when needed badly) -- "
set mouse=a

" -- better line number -- "
" on normal mode, sets current line as current line and others as 
" relative
set number relativenumber
" on insert mode, this is not needed, so restores normal line numbers
augroup numbertoggle
	autocmd!
	autocmd BufEnter,FocusGained,InsertLeave * set relativenumber
	autocmd BufLeave,FocusLost,InsertEnter   * set norelativenumber
augroup END

" -- Tab width -- "
" for using tabs for indenting
set sw=4
set tabstop=4

" -- Cursor style change depending on mode -- "
let &t_ti.="\e[1 q"
let &t_SI.="\e[5 q"
let &t_EI.="\e[1 q"
let &t_te.="\e[0 q"

" -- highlight the status bar when in insert mode -- "
if version >= 700
	au InsertEnter * hi StatusLine ctermfg=235 ctermbg=2
	au InsertLeave * hi StatusLine ctermbg=230 ctermfg=12
endif

" -- highlight trailing spaces in annoying red -- "
highlight ExtraWhitespace ctermbg=1 guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()


" ---- General Keyboard Shortcuts ---- "

inoremap <C-M-j> <ESC>ji
inoremap <C-M-k> <ESC>ki

" -- set leader key to comma -- "
let mapleader = ","

" -- Rename current file, via Gary Bernhardt -- "
function! RenameFile()
	let old_name = expand('%')
	let new_name = input('New file name: ', expand('%'))
	if new_name != '' && new_name != old_name
		exec ':saveas ' . new_name
		exec ':silent !rm ' . old_name
		redraw!
	endif
endfunction
map <leader>r :call RenameFile()<cr>

" -- exit insert with one hand! -- "
inoremap jk <ESC>

" -- window/tab related keys -- "
nnoremap <C-s> :w<CR>
inoremap <C-s> <Esc>:w<CR>i
map <C-t> :tabnew<CR>
map <C-h> :tabp<CR>
map <C-l> :tabn<CR>

nnoremap <C-w> :q<CR>
inoremap <C-w> <Esc>:q<CR>

" -- Duplicate line -- "
vnoremap <C-S-D> y'>p<CR>
nnoremap <C-S-D> yypk<CR>

" -- Cut line -- "
vnoremap <C-S-k> d
nnoremap <C-S-k> dd

" -- move lines up and down -- "
nnoremap <C-j> :m .+1<CR>==
nnoremap <C-k> :m .-2<CR>==
inoremap <C-j> <Esc>:m .+1<CR>==gi
inoremap <C-k> <Esc>:m .-2<CR>==gi
vnoremap <C-j> :m '>+1<CR>gv=gv
vnoremap <C-k> :m '<-2<CR>gv=gv

" -- copy-paste systemwide (linux) -- "
vmap <C-c> y:call system("xclip -i -selection clipboard", getreg("\""))<CR>:call system("xclip -i", getreg("\""))<CR>
nmap <C-v> :call setreg("\"",system("xclip -o -selection clipboard"))<CR>p
" https://stackoverflow.com/a/20902777

" -- File format specific things -- "
" - for rmarkdown (.rmd files) - "
autocmd FileType rmd map <F5> :!echo<space>"require(rmarkdown);<space>render('<c-r>%')"<space>\|<space>R<space>--vanilla<enter>


" -------- Plugin Related -------- "


" ---- NerdTree related ---- "
map <C-o> :NERDTreeToggle<CR>

" ---- NerdCommenter related ---- "
nmap <C-_> ,c<space>
imap <C-_> <Esc>,c<space>i
vmap <buffer> <C-_> ,c<space>
" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1
" Use compact syntax for prettified multi-line comments
"let g:NERDCompactSexyComs = 1
" Add your own custom formats or override the defaults
let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }
" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1
" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1

" ---- Ctrlp related ---- "
let g:ctrlp_map = '<leader>ff'
nmap <C-M-f> ,ff
imap <C-M-f> <Esc>,ff
let g:ctrlp_max_height = 25
"let g:ctrlp_working_path_mode = 0
let g:ctrlp_match_window_reversed = 0

" use silver searcher for ctrlp
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'


" ---- Multi Select related (like sublime) ---- "
let g:multi_cursor_next_key='<C-n>'
"let g:multi_cursor_prev_key='<C-z>'

" ---- PDV ---- "
" phpDocumentor auto comments related
"let g:pdv_template_dir = $HOME ."/.vim/bundle/pdv/templates_snip"
let g:pdv_template_dir = $HOME ."/.local/share/nvim/plugged/pdv/templates_snip"
"nnoremap <buffer> <C-m> :call pdv#DocumentWithSnip()<CR>
nnoremap <buffer> <C-m> :silent! call pdv#DocumentWithSnip()<CR>


" ---- roxma/LanguageServer-php-neovim related ---- "
"autocmd FileType php LanguageClientStart
" pip3 requirements
let g:python_support_python3_requirements = add(get(g:,'python_support_python3_requirements',[]),'neovim')

" ---- ultisnip related ---- "
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
inoremap <silent><expr><TAB> pumvisible() ? "\<C-n>" : "\<TAB>"
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<s-tab>"
let g:UltiSnipsSnippetsDir='~/.local/share/nvim/plugged/vim-snippets/UltiSnips'

" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
" -- Solution to: UltiSnips requires py >= 2.6 or any py3
" yaourt -S python-pip
" pip3 install --user neovim


" ---- dragvisuals ---- "
runtime plugin/dragvisuals.vim

vmap  <expr>  <LEFT>   DVB_Drag('left')
vmap  <expr>  <RIGHT>  DVB_Drag('right')
vmap  <expr>  <DOWN>   DVB_Drag('down')
vmap  <expr>  <UP>     DVB_Drag('up')
vmap  <expr>  D        DVB_Duplicate()

" Remove any introduced trailing whitespace after moving...
let g:DVB_TrimWS = 1


" ---- Denite plugin related ---- "

" Change mappings.
call denite#custom#map(
	\ 'insert',
	\ '<C-j>',
	\ '<denite:move_to_next_line>',
	\ 'noremap'
	\)
call denite#custom#map(
	\ 'insert',
	\ '<C-k>',
	\ '<denite:move_to_previous_line>',
	\ 'noremap'
\)

let g:search_term = ''
set viminfo^=h
function! FindText()
  let g:search_term = input('Search for: ', '')
  if g:search_term != ''
	"exec ':/' . g:search_term . "\<CR>"
	"normal ':/' . g:search_term . "\<CR>"
	let @/ = g:search_term
	"execute 'normal /' . g:search_term . "\<CR>"
	"let @/ = '\<' . g:search_term . '\>'
	"let @/='\<<C-R>=expand("<' . g:search_term  . '>")<CR>\>'<CR>:set hls<CR>
	"let g:highlighting = 1
	normal n
	"return ":silent set hlsearch\<CR>"
  endif
endfunction
map <leader>f :call FindText()<cr>
nmap <C-f> ,f
imap <C-f> <Esc>,f

function! FindTextNext()
	if g:search_term != ''
		"exec ':/' . g:search_term . "<CR>"
		normal n
	endif
endfunction
nnoremap <F3> :call FindTextNext()<CR>

" Add custom menus
let s:menus = {}

let s:menus.my_commands = {
	\ 'description': 'Example commands'
	\ }
let s:menus.my_commands.command_candidates = [
	\ ['Split the window', 'vnew'],
	\ ['Set syntax: php', 'set filetype=php'],
	\ ['Set syntax: html', 'set filetype=html'],
	\ ['Set syntax: css', 'set filetype=css'],
	\ ['Set syntax: js', 'set filetype=js'],
	\ ['Show invisibles', 'set list'],
	\ ['Hide invisibles', 'set nolist'],
	\ ['Find in this file', 'call FindText()'],
	\ ['Find in files', 'CtrlP'],
	\ ['Remove Trailing Spaces', 'RemoveTrailingSpaces'],
\ ]

call denite#custom#var('menu', 'menus', s:menus)


"nnoremap <silent>[menu]g :Unite -silent -start-insert menu:my_commands<CR>
"nnoremap <Leader>c :<C-U>Denite menu:my_commands -start-insert -ignorecase<CR>
nnoremap <Leader>p :Denite menu:my_commands -ignorecase<CR>
nnoremap <C-P> :Denite menu:my_commands -ignorecase<CR>

" ---- Minimap related ---- "
let g:minimap_update='<leader>mu'
let g:minimap_toggle='<leader>mt'